import fs from 'fs';
import path from 'path';

export interface DirTreeType {
  name: string;
  path: string;
  id: number;
  type: string;
  children?: Array<DirTreeType>;
  parentId: number | null;
}

let uid = 0;

const getRoot = (url: string) => {
  const root = {
    name: path.basename(url),
    path: url,
    type: 'directory',
    children: getDirectoryTree(url, uid),
    id: uid++,
    parentId: null,
  };

  return [root] as Array<DirTreeType>;
};

const getDirectoryTree = (url: string, parentId: number) => {
  const children: Array<DirTreeType> = [];
  const dirs = fs.readdirSync(url);
  if (dirs && Array.isArray(dirs)) {
    dirs.forEach((dir, index) => {
      const dirpath = path.resolve(url, dir);
      const stat = fs.statSync(dirpath);
      if (stat.isDirectory()) {
        children.push({
          name: dir,
          path: dirpath,
          type: 'directory',
          children: getDirectoryTree(dirpath, uid),
          id: uid++,
          parentId,
        });
      } else {
        children.push({
          name: dir,
          path: dirpath,
          id: uid++,
          type: 'file',
          parentId,
        });
      }
    });
  }

  return sortDirTree(children);
};

function sortDirTree(tree: Array<DirTreeType>) {
  const dirs: Array<DirTreeType> = [],
    files: Array<DirTreeType> = [];
  tree.forEach((item) => {
    if (item.type == 'directory') {
      dirs.push(item);
    } else {
      files.push(item);
    }
  });
  return dirs.concat(files);
}

export function getCurrentId() {
  return uid++;
}

export function makeDir(url: string, name: string) {
  fs.mkdirSync(path.resolve(url, name));
}

export function makeFile(url: string, name: string) {
  fs.writeFileSync(path.resolve(url, name), '');
}

export default getRoot;
